package com.gagakuai.bpm.mqlistener.camunda.handler.sync;

import com.alibaba.fastjson.JSON;

import com.gagakuai.bpm.common.constants.BpmMetaConstants;
import com.gagakuai.bpm.common.enums.BusinessCodeEnum;
import com.gagakuai.bpm.common.exception.BpmException;
import com.gagakuai.bpm.dao.mapper.camunda.ActIdUserMapper;
import com.gagakuai.bpm.domian.entity.camuda.ActIdUser;
import com.gagakuai.bpm.mqlistener.camunda.baseproxy.BaseConsumer;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.Objects;

/*
 * @program: bpm_server
 * @description: bpm同步人员信息消费者
 * @author: houhong
 * @create: 2022-05-17 17:11
 */
@Slf4j
@Component
public class BpmSyncAccountConsumer implements BaseConsumer, ApplicationContextAware {


    @Autowired
    private ActIdUserMapper actIdUserMapper;

    private ApplicationContext applicationContext;

    @Qualifier(value = "transactionManager")
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    /*
     * @param message 消息
     * @param channel 通道
     * @return
     * @Author houhong
     * @Description //TODO 实际类消费消息
     * @Date 11:00 上午 2022/3/25
     */
    @Override
    public void consume(Message message, Channel channel,String messageType) throws Exception {


        log.info("=============开始进行同步人员================");
        String str = new String(message.getBody());
        //用户
        ActIdUser actIdUser = JSON.parseObject(str, ActIdUser.class);
        actIdUser.setLast(actIdUser.getFirst());

        //操作类型
        String operType = actIdUser.getOperType();

        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = transactionManager.getTransaction(def);

        try {
            ActIdUser hasExit = actIdUserMapper.selectByPrimaryKey(actIdUser.getId());

            if (BpmMetaConstants.SYNC_TYPE_CREATE.equals(operType)) {

                if (Objects.nonNull(hasExit)) {

                    //Todo ：以后可以在这里处理新增加的逻辑
                } else {
                    int result = actIdUserMapper.insertSelective(actIdUser);

                    if (result <= 0) {
                        throw new BpmException(BusinessCodeEnum.BPM_SYNC_ACCOUNT_FAILED);
                    }
                }

            } else if (BpmMetaConstants.SYNC_TYPE_UPDATE.equals(operType)) {

                if (Objects.nonNull(hasExit)) {

                    actIdUserMapper.updateByPrimaryKeySelective(actIdUser);
                }

            } else if (BpmMetaConstants.SYNC_TYPE_DELETE.equals(operType)) {

                actIdUserMapper.deleteByPrimaryKey(actIdUser.getId());
            }
            //提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            throw new BpmException(BusinessCodeEnum.BPM_SYNC_ACCOUNT_FAILED);
        } finally {

        }

        log.info("=============进行同步人员完毕================");

    }
}